package avicit;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import java.util.List;

public class RocketMQConsumer2 {
    // 使用与生产者相同的TOPIC_NAME
    private static final String TOPIC_NAME = "TestTopic";
    private static final String CONSUMER_GROUP = "TestConsumerGroup";

    public static void main(String[] args) throws Exception {
        // 1. 创建消费者实例，指定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(CONSUMER_GROUP);

        // 2. 设置NameServer地址（与生产者相同）
        consumer.setNamesrvAddr("10.216.38.233:8000");

        // 3. 订阅主题和标签（与生产者发送的标签一致）
        consumer.subscribe(TOPIC_NAME, "TagA");

        // 4. 注册消息监听器
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                            ConsumeConcurrentlyContext context) {
                // 遍历收到的消息
                for (MessageExt msg : msgs) {
                    // 打印接收到的消息内容
                    System.out.println("收到消息: " + new String(msg.getBody()));
                }
                // 返回消费成功状态
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        // 5. 启动消费者
        consumer.start();
        System.out.println("消费者已启动，等待消息...");
    }
}